<script lang="ts" setup>

import
{ref, reactive, onMounted, watch} from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import {useUserStore} from '@/stores/user.js'
import {updateUserInfoAPI} from '@/apis/user'
import {getDetailOrderListAPI} from '@/apis/order'
import {getAddressListAPI} from '@/apis/address';
import {getShopById} from "@/apis/shopApi.js";
import MapContainer from "@/components/base/MapContainer.vue";
import {getRouteByOrderIdAPI} from "@/apis/logistics.js";

const ruleFormRef = ref<FormInstance>()

const form = reactive({
  realName: useUserStore().userInfo.realname||'',
  identityNum:useUserStore().userInfo.identityNum||'',
  canChange:useUserStore().isAuth
})

const myOrder=ref({
  wait_pay:0,
  wait_delivery:0,
  wait_receive:0,
  refund:0,
})

const shippedOrders = ref([]);
const selectedOrderId = ref(null);
const activeRoute = ref({ startLngLat: null, endLngLat: null, mapId: 'logistics-map' });
const isMapVisible = ref(false);

onMounted(()=>{
  getShippedOrders()
  getOrderStats()
})

// 获取所有待收货的订单列表
const getShippedOrders = async () => {
  const orderRes = await getDetailOrderListAPI(useUserStore().userInfo.uid);
  if (orderRes.code === 200 && orderRes.data) {
    const pendingReceiptOrders = orderRes.data.filter(o => o.status === 3);
    shippedOrders.value = pendingReceiptOrders.map(o => ({
      ...o,
      displayText: `订单号: ${o.oid} - ${o.goods[0]?.title || '商品'}`
    }));

    // 默认选中第一个
    if (shippedOrders.value.length > 0) {
      selectedOrderId.value = shippedOrders.value[0].oid;
    }
  }
};

// 获取订单统计数据
const getOrderStats = async () => {
  const orderRes = await getDetailOrderListAPI(useUserStore().userInfo.uid);
  if (orderRes.code === 200 && orderRes.data) {
    const orders = orderRes.data;
    
    // 重置统计
    myOrder.value.wait_pay = 0;
    myOrder.value.wait_delivery = 0;
    myOrder.value.wait_receive = 0;
    myOrder.value.refund = 0;
    
    // 统计各状态订单数量
    orders.forEach(order => {
      switch (order.status) {
        case 0: // 待付款
          myOrder.value.wait_pay++;
          break;
        case 2: // 待发货
          myOrder.value.wait_delivery++;
          break;
        case 3: // 待收货（已发货）
          myOrder.value.wait_receive++;
          break;
        case 5: // 退款
          myOrder.value.refund++;
          break;
        default:
          // 其他状态暂不统计
          break;
      }
    });
  }
};

// 当选择的订单变化时，调用新接口获取路线
watch(selectedOrderId, async (newOid) => {
  if (!newOid) {
    isMapVisible.value = false;
    return;
  }

  try {
    const routeRes = await getRouteByOrderIdAPI(newOid);
    if (routeRes.code === 200 && routeRes.data) {
      activeRoute.value = {
        startLngLat: routeRes.data.start,
        endLngLat: routeRes.data.end,
        mapId: `logistics-map-${newOid}`
      };
      isMapVisible.value = true;
    } else {
      isMapVisible.value = false;
      ElMessage.error('获取物流路线失败');
    }
  } catch (e) {
    isMapVisible.value = false;
    ElMessage.error('获取物流路线异常');
    console.error(e);
  }
});

const rules={
  realName:[
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在2-10个字符', trigger: 'blur' },
  ],
  identityNum:[
    { required: true, message: '请输入身份证号码', trigger: 'blur' },
    { min: 18, max: 18, message: '请输入有效18位身份证号码', trigger: 'blur' },
  ]
}

const dialogFormVisible = ref(false)

const submitRealName = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      form.canChange=true;
      dialogFormVisible.value=false
      useUserStore().authRealName(form)
      updateUserInfoAPI(useUserStore().userInfo)
      ElMessage({
        message: '实名认证成功',
        type: 'success',
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

</script>

<template>
  <div class="UC_home">
    <div class="top">

      <el-row  >
        <el-col :span="4">
          <img class="userImg" style="width: 120px;height: 120px" :src="useUserStore().getAvatar" alt="">

        </el-col>
        <el-col :span="18">
          <div class="userName">
            <span style="font-size: 24px;color: #11192d">{{useUserStore().userInfo.username}}</span>&nbsp
            <el-tag v-show="useUserStore().userInfo.role==='expert'" type="warning">
              <el-icon><Select /></el-icon>
              专家认证
            </el-tag>&nbsp

            <el-tag type="success" v-if="useUserStore().isAuth">已实名</el-tag>
            <el-tag type="info" v-if="!useUserStore().isAuth">未实名</el-tag>
          </div>
          <div class="userId" style="margin-top: 10px">
            <span style="font-size: 14px;color: #7c889c">我的账号 {{useUserStore().userInfo.uid}}</span>
            <span class="authRealName" @click="dialogFormVisible = true" >实名认证</span>
          </div>
        </el-col>
      </el-row>

      <el-row  style="text-align: center;color: #121a2f">
        <el-col :span="6">
          <div>
            <span style="font-size: 24px;">{{myOrder.wait_pay}}</span><br>
            <span style="font-size: 14px;">待付款</span>
          </div>

        </el-col>
        <el-col :span="6">
          <span style="font-size: 24px;">{{myOrder.wait_delivery}}</span><br>
          <span style="font-size: 14px;">待发货</span>
        </el-col>
        <el-col :span="6">
          <span style="font-size: 24px;">{{myOrder.wait_receive}}</span><br>
          <span style="font-size: 14px;">待收货</span>
        </el-col>
        <el-col :span="6">
          <span style="font-size: 24px;">{{myOrder.refund}}</span><br>
          <span style="font-size: 14px;">退款</span>
        </el-col>
      </el-row>
    </div>

    <div class="express">
      <div class="express-header">
        <span style="font-size: 16px;font-weight: bold;margin-left: 20px">我的物流</span>
        <el-select v-if="shippedOrders.length > 0" v-model="selectedOrderId" placeholder="选择订单" style="margin-left: 20px; width: 240px;">
          <el-option
              v-for="order in shippedOrders"
              :key="order.oid"
              :label="order.displayText"
              :value="order.oid"
          />
        </el-select>
      </div>

      <template v-if="isMapVisible">
        <MapContainer
            style="margin-top: 10px;
            border-radius: 10px;
            width: 900px;
            height: 400px;
            margin-left: auto;
            margin-right: auto"
            :start-lng-lat="activeRoute.startLngLat"
            :end-lng-lat="activeRoute.endLngLat"
            :map-id="activeRoute.mapId"
        />
      </template>
      <template v-else>
        <el-empty description="暂无物流信息" />
      </template>
    </div>


  </div>

  <el-dialog v-model="dialogFormVisible" title="实名认证" width="500" >
    <el-form :model="form"
             :rules="rules"
             v-show="!form.canChange"
             ref="ruleFormRef"
             label-width="auto">
      <el-form-item label="真实姓名" prop="realName">
        <el-input v-model="form.realName" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="身份证号码" prop="identityNum">
        <el-input v-model="form.identityNum" autocomplete="off"/>
      </el-form-item>
    </el-form>

    <el-descriptions
        title="当前实名信息"
        v-show="form.canChange"
        :column="1"
        border
    >
      <el-descriptions-item label="姓名 " >
        <span style="color:#999;">{{ form.realName }}</span>
      </el-descriptions-item>
      <br>
      <el-descriptions-item label="身份证号">
        <span style="color:#999;">{{ form.identityNum }}</span>
      </el-descriptions-item>
      <br>

    </el-descriptions>

    <template #footer>
      <div class="dialog-footer">

        <template v-if="false">
          <el-button type="danger" @click="form.canChange=false">
            更换实名
          </el-button>
        </template>
        <template v-else-if="!form.canChange">
          <el-button @click="dialogFormVisible = false;form.canChange=false">取消</el-button>
          <el-button type="primary" @click="submitRealName(ruleFormRef)">
            提交
          </el-button>
        </template>
      </div>
    </template>
  </el-dialog>

</template>

<style scoped lang="less">

.UC_home{
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  justify-content: center;
  align-items: flex-start;
  align-content: stretch;
  gap: 20px
}

.el-row {
  margin-bottom: 20px;
}

.el-col div:hover{
  cursor: pointer;
  color: #409EFF;
}

.top{
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  justify-content: center;
  //align-items: center;
  //align-content: stretch;

  width: 990px;
  height: 260px;
  background-color: white;
  border-radius: 10px;

  padding: 0 20px;
}
.express{
  width: 990px;
  min-height: 400px;
  height: auto;
  background-color: white;
  border-radius: 10px;
  padding: 20px 20px;
}

.express-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.likes{
  width: 990px;
  height: 500px;
  background-color: white;
  border-radius: 10px;
  padding: 20px 20px;
}

.authRealName{
  float: right;
  font-size: 14px;
  color: #7c889c
}

.authRealName:hover{
  color: #39bf3e;
  cursor:pointer;
}

</style>
